package com.ysucode.controller.user.advice;

import com.ysucode.annotation.MyLogger;
import com.ysucode.constant.Login;
import com.ysucode.domain.User;
import com.ysucode.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 自定义登录成功的行为
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;

    //AuthenticationException里封装了用户登陆成功的信息
    @Override
    @MyLogger(value = "用户登录", flag = true)
    public void onAuthenticationSuccess(HttpServletRequest req,
                                        HttpServletResponse res,
                                        Authentication authentication)
            throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        User user = userService.getByUsername(username);
        HttpSession session = req.getSession();
        log.debug(Login.LOG_SUCCESS);
        session.setAttribute("user", user); //表示用户登录
        res.sendRedirect("/ojHome");
    }

}